package org.example.plugins;

import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.baomidou.dynamic.datasource.creator.DataSourceProperty;
import com.baomidou.dynamic.datasource.creator.DefaultDataSourceCreator;
import lombok.extern.slf4j.Slf4j;
import org.example.entity.Master;
import org.example.mapper.MasterMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.util.List;

@Slf4j
@Component
public class CommandAddSource implements CommandLineRunner {

    @Autowired
    private DefaultDataSourceCreator dataSourceCreator;
    @Autowired
    private DataSource dataSource;
    @Autowired
    private MasterMapper masterMapper;

    @Override
    public void run(String... args) throws Exception {
        DynamicRoutingDataSource ds = (DynamicRoutingDataSource) dataSource;
        List<Master> masters = masterMapper.queryAllMaster();
        masters.forEach(it -> {
            DataSourceProperty dataSourceProperty = new DataSourceProperty();
            BeanUtils.copyProperties(it, dataSourceProperty);
            DataSource dataSource = dataSourceCreator.createDataSource(dataSourceProperty);
            ds.addDataSource(it.getPoolName(), dataSource);
        });
        ds.getDataSources().keySet().forEach(log::info);
    }
}
